<template>
  <div class="lb-login" :style="{ 'backgroundImage': 'url(' + loginBg + ')' }">
    <div class="login-content">
      <div class="left-box" v-html="lHtml"></div>
      <div class="right-box">
        <el-form @submit.native.prevent ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form"
          autocomplete="on" label-position="left">
          <div class="title-container">
            <div class="logo-top-img" v-html="tHtml"></div>
          </div>
          <el-form-item prop="username">
            <span class="svg-container">
              <i class="iconfont icon-username"></i>
            </span>
            <el-input ref="username" v-model="loginForm.username" placeholder="请输入账号" name="username" type="text"
              tabindex="1" autocomplete="on" />
          </el-form-item>
          <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
            <el-form-item prop="passwd">
              <span class="svg-container">
                <i class="iconfont icon-mima"></i>
              </span>
              <el-input :key="passwordType" ref="password" v-model="loginForm.passwd" :type="passwordType"
                placeholder="请输入密码" name="passwd" tabindex="2" autocomplete="on" @keyup.native="checkCapslock"
                @blur="capsTooltip = false" @keyup.enter.native="handleLogin" />
            </el-form-item>
          </el-tooltip>
          <el-form-item prop="codeText">
            <span class="svg-container">
              <i class="iconfont iconyanzhengma"></i>
            </span>
            <el-input ref="codeText" v-model="loginForm.codeText" placeholder="请输入验证码" name="codeText" type="text"
              tabindex="3" autocomplete="on" style="width: 180px" />
            <div class="code-text" @click="refreshCode">
                <lb-identify :identifyCode="identifyCode" :fontSizeMin="30" :fontSizeMax="30"></lb-identify>
            </div>
          </el-form-item>
          <el-button :loading="loading" type="primary"
            style="width: 100%;height: 46px;display: block;margin: 30px auto 0;color: #fff;border-radius: 4px;background: linear-gradient(90deg,#19b4f1,#0e73e8)!important;"
            @click.native.prevent="handleLogin">登录</el-button>
        </el-form>
      </div>
    </div>
    <div class="lb-footer-html" v-html="fHtml"></div>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
export default {
  name: 'Login',
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6 || value.length > 30) {
        callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }
    const validateCodeText = (rule, value, callback) => {
      if (this.loginForm.codeText.toLowerCase() == this.identifyCode.toLowerCase()) {
        callback()
      } else {
        callback(new Error('验证码不正确'))
      }
      // if (value === '') {
      //   callback(new Error('请输入验证码'))
      // } else if (!/^[a-z0-9]+$/.test(value) || value.length !== 4) {
      //   callback(new Error('验证码不正确'))
      // } else {
      //   callback()
      // }
    }
    return {
      loginBg: require('@/./style/image/login_bg.png'),
      fHtml: '',
      lHtml: '',
      tHtml: '',
      identifyCode: '',
      authTime: 0,
      timer: null,
      loginForm: {
        username: '',
        passwd: '',
        codeText: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: this.$reg.isNotNull, reg_type: 2, text: '账号' }],
        passwd: [{ required: true, trigger: 'blur', validator: validatePassword }],
        codeText: [{ required: true, trigger: 'blur', validator: validateCodeText }]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {}
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.passwd === '') {
      this.$refs.passwd.focus()
    }
    this.makeCode()
    this.getCopyrightInfo()
  },
  computed: {
    ...mapState({
      routesItem: state => state.routes
    })
  },
  methods: {
    ...mapMutations(['changeRoutesItem']),
    async getCopyrightInfo() {
      let { code, data } = await this.$api.base.getConfig()
      if (code !== 200) return
      let { copyright, login_type: type, icp, login_logo: logo, login_left: left, login_title: title } = data
      if (!icp) return
      let recordcode = type === 2 ? icp.replace(/[^0-9]/ig, '') : ``
      let image = type === 1 ? `` : ``
      let href = type === 1 ? `https://beian.miit.gov.cn/` : `https://www.beian.gov.cn/portal/registerSystemInfo?recordcode=${recordcode}`
      this.fHtml = `<div class="flex-y-center c-base c-title ">
						<p style="margin-right: 10px;">${copyright}</p>
						备案号：${image} 
						<a class="c-base c-title " href="${href}" target="_blank">${icp}</a>
					</div>`
      this.lHtml = `<image class="left-sm" src="${left}"></image>`
      this.tHtml = `<image class="mr-sm" src="${logo}"></image>`
    },
    checkCapslock({ shiftKey, key } = {}) {
      if (key && key.length === 1) {
        if ((shiftKey && (key >= 'a' && key <= 'z')) || (!shiftKey && (key >= 'A' && key <= 'Z'))) {
          this.capsTooltip = true
        } else {
          this.capsTooltip = false
        }
      }
      if (key === 'CapsLock' && this.capsTooltip === true) {
        this.capsTooltip = false
      }
    },
    setCookie(cname, cvalue, exdays) {
      var d = new Date()
      d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000))
      var expires = 'expires=' + d.toGMTString()
      document.cookie = `${cname}=${cvalue};${expires};`
    },
    refreshCode() {
      this.makeCode()
    },
    makeCode() {
      this.identifyCode = Math.random().toString(36).substr(2, 4)
      this.setCookie('codeText', this.identifyCode, 3)
    },
    handleLogin() {
      this.loading = true
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.$api.base.login(this.loginForm).then(res => {
            this.loading = false
            if (res.code === 200) {
              this.changeRoutesItem({ key: 'userInfo', val: res.data.user })
              window.localStorage.setItem('massage_minitk', res.data.token)
              window.localStorage.setItem('massage_ms_username', res.data.user.username)
              window.localStorage.setItem('massage_userInfo', JSON.stringify(res.data.user))
              this.$router.push('/')
            } else {
              this.refreshCode()
            }
          })
        } else {
          this.loading = false
          return false
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }
  }
}
</script>

<style lang="scss">
$bg: #283443;
$light_gray: #fff;
$cursor: #fff;
@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .lb-login .el-input input {
    color: $cursor;
  }
}

.login-content {
  width: 1000px;
  height: 450px;
  margin: 10% auto 0 auto;
  background-color: #fff;
  border-radius: 10px;
  display: flex;
}

.left-box {
  background-size: cover !important;
  width: 50%;
  height: 100%;
  border-radius: 10px 0 0 10px;
}

.left-sm {
  width: 500px;
  height: 450px;
  border-radius: 10px 0 0 10px;
}

.lb-login {
  .el-input {
    display: inline-block;
    height: 40px;
    width: 80%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 0px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px #fff inset !important;
        -webkit-text-fill-color: #000 !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid #dcdfe6;
    background-color: #fff;
    border-radius: 5px;
    color: #454545;
  }
}

.logo-top-img {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 50px;
  margin-bottom: 32px;
}

.lb-login .el-input input {
  background: transparent;
  border: 0px;
  -webkit-appearance: none;
  border-radius: 0px;
  padding: 12px 0px;
  color: #333;
  height: 40px;
  caret-color: #333;
}

.lb-footer-html {
  width: 100%;
  height: 49px;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10;
  font-size: 13px;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
}

.c-title {
  color: #333;
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.lb-login {
  width: 100%;
  height: 100vh;
  background-size: cover !important;
  background-color: #f2f2f2;
  display: flex;
  flex-direction: column;

  .login-form {
    position: absolute;
    margin: auto;
    box-sizing: border-box;
    width: 500px;
    max-width: 100%;
    padding: 60px;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 0px 10px;
    color: $dark_gray;
    vertical-align: middle;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 22px;
      color: #666;
      margin: 0px auto 25px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 0px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  .code-text {
    width: 160px;
    height: 37px;
    position: absolute;
    right: 0px;
    bottom: 5px;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}
</style>
